/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hanserver.action.hancadsa.finished;

import br.com.sales.hanserver.action.hancadsa.finished.query.FinishedSaleQuery;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author v
 */
public class FinishedSalesAction extends FinishedSaleQuery {

    public FinishedSalesAction() {
    }

    public void finished(Map values) {
        try {
            long sequence = getMaxSequenceSale();
            try {

                insertSale(sequence,
                        new Timestamp(new SimpleDateFormat().parse(values.get("DT_REGISTER").toString()).getTime()),
                        getSeller(values.get("NM_USER").toString()),
                        !"".equals(values.get("CLIENT")) && values.get("CLIENT") != null ? Long.parseLong(values.get("CLIENT").toString()) : null,
                        Double.parseDouble(values.get("TOTAL").toString()),
                        "".equals(values.get("DESC")) ? 0 : Integer.parseInt((String) values.get("DESC")));

            } catch (Exception ex) {
                Logger.getLogger(FinishedSalesAction.class.getName()).log(Level.INFO, "Erro insert venda " + values, ex);
            }
            List<Map> items = (List<Map>) values.get("ITEM_SALES");

            for (Map item : items) {
                Long sequenceProduct = Long.parseLong(item.get("ID_PRODUCT").toString());
                int count = Integer.parseInt(item.get("COUNT").toString());
                try {
                    insertItemSale(
                            Double.parseDouble(item.get("VL_PRICE").toString()),
                            count,
                            sequence,
                            sequenceProduct);
                } catch (Exception ex) {
                    Logger.getLogger(FinishedSalesAction.class.getName()).log(Level.INFO, "Erro insert venda item " + values, ex);
                }
                try {
                    updateProduct(count, sequenceProduct);
                } catch (Exception ex) {
                    Logger.getLogger(FinishedSalesAction.class.getName()).log(Level.INFO, "Update Produto venda " + values, ex);
                }
            }

        } catch (Exception ex) {
            Logger.getLogger(FinishedSalesAction.class.getName()).log(Level.INFO, "Erro insert venda geral", ex);
        }
    }
}
